<?php

namespace App\Http\Controllers;

use App\Models\Alarm;
use App\Models\Enterprise;
use App\Models\ReportCar;
use App\Models\Vehicle;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use PhpClickHouseLaravel\RawColumn;
use App\Models\Api\File;
use App\Models\Charger;
use App\Models\ClusterReport;
use App\Models\EnergyStorager;
use App\Models\ESCluster;
use App\Models\Task;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class WorkspaceController extends Controller
{
    protected function count_online($enterprise)
    {
        $end = strtotime(now());
        $start = strtotime('-30 day', $end);
        for ($i = 0; $i < 30; $i++) {
            $date  = date('Y-m-d', $start);
            if ($enterprise) {
                $arr[$date] = rand(1200, 1500);
            } else {
                $arr[$date] = 0;
            }
            $start = strtotime('+1 day', $start);
        }

        return $arr;
    }

    protected function super_home()
    {
    }

    public function home(Request $request)
    {
    }

    public function super_screen()
    {
    }
    protected function statistics()
    {
        $today = time();
        $init = strtotime(env('APP_START', '2023-05-23'));
        $data['security_days'] = floor(($today - $init) / (3600*24));
        $data['predict_15days'] = 1;
        $data['rechargeable_power'] = "369.1";
        $data['dischargeable_power'] = "473.5";
        $data['current_power'] = "198.3";

        return $data;
    }
    protected function cluster_real_time($cluster_id)
    {
        $data = ClusterReport::find($cluster_id);
        $data['power'] = $data['voltage'] * $data['current'];
        // $data['total_voltage'] = '687';
        // $data['total_current'] = '100';
        // $data['average_SOC'] = '100';
        // $data['average_SOH'] = '11';
        return $data;
    }
    protected function unit_status($unit_id)
    {
        $data = ESCluster::where('e_s_unit_id', $unit_id)->get();
        return $data;
    }
    protected function cluster_alarm($cluster_id)
    {
        $data = Alarm::where('e_s_cluster_id', $cluster_id)->get();
        return $data;
    }
    public function BigScreen(Request $request)
    {
        try {
            $unit_id = $request->input('unit_id', '1');
            $e_s_cluster_id = $request->input('e_s_cluster_id', '1');
            $enterprise = $request->user()->enterprises()->first();
            $data['statistics'] = $this->statistics();
            $data['real_time_data'] = $this->cluster_real_time($e_s_cluster_id);
            $data['status'] = $this->unit_status($unit_id);
            $data['alarm'] = $this->cluster_alarm($e_s_cluster_id);
            if($enterprise){
                $data['enterprise'] = $enterprise;
            }
            if($request->user()->hasRole('超级管理员')){
                // $data = $this->super_screen();
            }
            return $this->respondSuccess($data);
        } catch (QueryException $e) {
            return $this->respondError($e->getMessage());
        }
    }

    public function ProvinceScreen(Request $request)
    {
        try {
            $province = $request->input('province');
            $data['energy_storagers']['avgSOH'] = 0;
            $data['energy_storagers']['avgCircleCount'] = 0;
            $data['energy_storagers']['leftLife'] = 0;
            $data['energy_storagers']['avgInternalResistance'] = 0;
            $data['energy_storagers']['avgSelfFire'] = 0;

            return $this->respondSuccess($data);
        } catch (QueryException $e) {
            return $this->respondError($e->getMessage());
        }
    }

    public function region(Request $request)
    {
        try {
            require app_path() . '/Helpers/address/data/a1.php';
            require app_path() . '/Helpers/address/data/a2.php';
            require app_path() . '/Helpers/address/data/a3.php';

            if (!$request->has('province')) {
                $data =  Arr::pluck($a1_data, 'name');
            } else {
                if (!$request->has('city')) {
                    $province = $request->input('province');
                    foreach ($a1_data as $key => $value) {
                        if (strstr($value['name'], $province)) {
                            $pid = $key;
                            break;
                        }
                    }
                    $citys = Arr::where($a2_data, function ($value, $key) use ($pid) {
                        return $value['pid'] == $pid;
                    });
                    $data = Arr::pluck($citys, 'name');
                } else {
                    $city = $request->input('city');
                    foreach ($a2_data as $key => $value) {
                        if (strstr($value['name'], $city)) {
                            $pid = $key;
                            break;
                        }
                    }
                    $districts = Arr::where($a3_data, function ($value, $key) use ($pid) {
                        return $value['pid'] == $pid;
                    });
                    $data = Arr::pluck($districts, 'name');
                }
            }
            return $this->respondSuccess($data);
        } catch (\Throwable $th) {
            return $this->respondError($th->getMessage());
        }
    }

    public function weather(Request $request)
    {
        $url = 'http://www.nmc.cn/rest/weather';
        $data = [
            'stationid' => $request->input('stationid', 54511),
            '_' => $request->input('time', strtotime("today")),
        ];

        $resp = Http::timeout(10)->get($url, $data);
        if ($resp->successful()) {
            return $resp->json();
        }
        Log::error('weather get:' . $url, $data);
        return $this->respondError('weather get:' . $url);
    }

    public function upload(Request $request)
    {
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $file = $request->file('file');
            $name =  Str::random(40) . '.' . $file->getClientOriginalExtension();

            switch ($request->input('type', 'other')) {
                case 'video':
                    $path = 'public/videos';
                    break;

                case 'image':
                    $path = 'public/images';
                    break;
                case 'csv':
                    $name =  date('YmdHis_') . substr(microtime(), 2, 6) . '.' . $file->getClientOriginalExtension();
                    $path = 'public/csvs';
                    break;
                default:
                    $path = 'public/others';
                    break;
            }
            $file = Storage::putFileAs($path, $request->file('file'), $name);
            $url = Storage::url($file);
            $data = [
                'filepath' => $file,
                'type' => $request->input('type') ?? 'other',
                'url'  => url($url),
            ];
            return $this->respondSuccess($data);
        }
        return $this->respondError('upload error!');
    }

    public function cloud_detection(Request $request)
    {
        $this->validate($request, [
            'e_s_cluster_id' => 'required',
        ], [
            'e_s_cluster_id.required' => 'e_s_cluster_id 不能为空',
        ]);
        $task['name'] = 'Cloud-detect'. date('-YmdHis');
        $task['dev_type'] = 'App\Models\ESCluster';
        $task['dev_id'] = $request->input('e_s_cluster_id', 1);
        $task['status'] = '成功';
        $task['estimate'] = 60;
        $task['user_id'] = $request->user()->id;

        $data = Task::create($task);
        return $this->respondSuccess($data);
    }
}
